import React, { useState, useEffect, useCallback, useMemo } from 'react'
import { useSearchParams, useNavigate } from 'react-router-dom'
import { Table, Button, Popconfirm, Row, Col,message,Upload } from 'antd'
import {PlusOutlined,DeleteOutlined,FormOutlined,DownloadOutlined,UnorderedListOutlined,UploadOutlined} from '@ant-design/icons'
import { useSelector } from 'react-redux'
import moment from 'moment'
import request,{host} from '@/utils/request'
import store from "@/store/index.js"

//引入组件
import Del from './Del'
import Tbutton from './Tbutton'
import ItemFrom from './ItemFrom'

function SchoolList() {
    //表单显示隐藏
    const [visible, setVisible] = useState(false);
    const user = useSelector(state => state.userInfo)
    const [search, setSearch] = useSearchParams(); 
    const [userlist, setUserlist] = useState([])

    const [classlist, setClasslist] = useState([])
    const [total, setTotal] = useState(0)
    const [params, setParams] = useState({
        page: search.get('page') * 1 || 1,
        size: search.get('size') * 1 || 10
    })
    //修改、删除按钮状态（true为禁用，false为可使用）
    const [isuse,setIsuse] = useState(true)

     //批量删除按钮状态（true为禁用，false为可使用）
    const [isDel,setDel] = useState(true)
    const [itemId,setId] = useState()//选中的选项Id
    //选中的分校信息
    const [rowInfo,setRowsinfo] = useState({})
    const [info,setInfo] = useState({})
    //获取分校列表
    const getData = useCallback(async () => {
        const { data } = await request.get('/city',{
            params:{
                page:params.page
            }
        })
        setUserlist(data.data.result)
        setTotal(data.data.total)
    }, [params])
    //获取班级信息
    const getclass = useCallback(async () => {
        const { data } = await request.get('/class',{
            params:{
                size:total
            }
        })
        setClasslist(data.data.result)
        setTotal(data.data.total)
    })
    useEffect(() => {
        getclass()
    }, [])

    //删除单个分校
    const remove = useCallback(async (id,record) => {
        console.log('我是删除按钮',id,record)
        const { data } = await request.delete('/city/' + id)
        if (data.code === 204) {
            getData();
            message.success('删除成功');
        }else{
            message.error('操作失败');
        }
    }, [getData])
    //批量删除学科
    const removeArr = useCallback(async (ids,record) => {
        const { data } = await request.delete('/city',{
            data:{
                ids:ids
            }
        })
        if (data.code === 204) {
            getData();
            message.success('删除成功');
        }else{
            message.error('操作失败');
        }
    }, [getData])
    //删除按钮，点击取消时执行这里的代码
    const cancel = (e) => {
        message.error('操作失败');
    };

    //添加单个分校
    const addItem = useCallback(async (values) => {
        const { data } = await request.post('/city',{
            name:values.name,
            code:values.code
        })
        if (data.code === 201) {
            getData();
            message.success('添加成功');
        }
    }, [getData]) 

    //修改单个分校
    const updataItem =async (values,id) => {
        const { data } = await request.put('/city/'+id,{
            name:values.name,
            code:values.code
        })
        if (data.code === 201) {
            getData();
            message.success('修改成功');
        }
    }

    //点击导出按钮
    const downloadFile = () => {
        const { userInfo: { _id } } = store.getState();
        request.post('/city/export', {
            userid: _id,
            ids: itemId,
            type: 'xls'
            // type:'json'  指定json格式
        }, {
            responseType: 'arraybuffer',
        }).then(res => {
            var blob = new Blob([res.data], {//这个里面的data 的二进制文件 创建一个文件对象
                type: 'application/vnd.ms-excel;charset=utf-8'
            })
            var downloadElement = document.createElement('a')//创建一个a 虚拟标签
            var href = window.URL.createObjectURL(blob) // 创建下载的链接
            downloadElement.href = href
            downloadElement.download =
                decodeURI(
                    res.headers['content-disposition'].split('filename=')[1]
                ) || '' // 下载后文件名
            document.body.appendChild(downloadElement)
            downloadElement.click() // 点击下载
            document.body.removeChild(downloadElement) // 下载完成移除元素
            window.URL.revokeObjectURL(href) // 释放掉blob对象
            message.success('导出成功')
        }).catch((res) => {
            console.log('res', res)
        })
    }

    //点击导入按钮
    const { userInfo: { authorization } } = store.getState()
    const props = {
        name: 'list',
        method: 'post',
        action: host + '/api/city/import',
        headers: {
            authorization: authorization,
        },

        onChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }

            if (info.file.status === 'done') {
                message.success(`${info.file.name}文件上传成功`);
                getData()

            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 文件上传失败`);
            }
        },
    };


    //点击整行显示整行的详情
    /* const onSelectRoW =(index,record,e)=>{
        showModal(index,record)
    } */
    //点击行内的编辑按钮
    const [texts,setText] = useState()
    const showModal = (id,record,text)=>{
        setVisible(true)
        setText(text)
        setRowsinfo(record)
    }
    //点击页码，当页码触发时
    useEffect(() => {
        getData()
    }, [params])

    //点击选框时
    const rowSelection = {
        onChange(selectedRowKeys,selectedRows) {
            setRowsinfo(selectedRows[0])
            //选中的选项为一项时
            if(selectedRowKeys.length===1){
                setIsuse(false)//修改按钮可使用
                setDel(true)
                //detailItem(selectedRowKeys)
            }else if(selectedRowKeys.length>1){
                //选中的选项两项或多项时
                setIsuse(true)//修改按钮失效 
                setDel(false)
            }else if(selectedRowKeys.length<=0){
                setDel(true)
                setIsuse(true)
            }
            setId(selectedRowKeys)
        }
    }
    //columns设置表格如何展示数据
    const columns = [
        {
            title: '序号',
            width: 60,
            render(text, record, index) {
                return index + 1
            }
        },
        {
            title: '分校城市',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '分校代号',
            dataIndex: 'code',
            key: 'code',
        },
        {
            title: '创建时间',
            dataIndex: 'add_time',
            width: '300px',
            render(text) {
                return moment(text).format('YYYY/MM/DD hh:mm:ss')
            }
        },
        {
            title: '操作',
            key: 'action',
            width: '300px',
            dataIndex: '_id',
            render(record,id) {
                return (
                    <>
                        {/* <Detail onSelectRoW={onSelectRoW} isuse={isuse}></Detail> */}
                        <Button type="link"  onClick={showModal.bind(null,record,id,'详情')}><UnorderedListOutlined />详情</Button>
                        <Button type="link" onClick={showModal.bind(null,record,id,'编辑')}><FormOutlined />编辑</Button>
                        <Popconfirm
                            title="确认删除"
                            onConfirm={remove.bind(null,record,id)}
                            onCancel={cancel}
                            okText="确定"
                            cancelText="取消">
                            <Button type="link"><DeleteOutlined />删除</Button>
                        </Popconfirm>
                        
                    </>
                )
            }
        }
    ]
    
    const pagination = {
        total,
        size: 'small',
        defaultCurrent: params.page,
        defaultPageSize: params.size,
        pageSize: params.size,
        current: params.page,
        onChange(page, size) {
            setParams({
                page,
                size
            })
            // 修改url地址参数
            setSearch({
                page,
                size
            })
        }
    }

    return (
        <div>
            <Row style={{marginBottom:'5px',background:'#f0f2f5',padding:0}}>
                <Col> 
                    {/* 添加按钮 */}
                    <Tbutton methods={addItem}><PlusOutlined />添加</Tbutton>
                    {/* 修改按钮 */}
                    <Tbutton methods={updataItem} isuse={isuse} rowInfo={rowInfo}><FormOutlined />修改</Tbutton>
                    {/* 删除按钮 */}
                    <Del remove={remove} itemId={itemId} isuse={isuse}>删除</Del>
                    <Del remove={removeArr} itemId={itemId} isuse={isDel}>批量删除</Del>
                    <Button onClick={downloadFile}
                     style={{
                        color:'#ffbf4d',
                        border:'1px solid #ffbf4d',
                        marginRight:'10px'}}
                        icon={<DownloadOutlined />}>导出
                    </Button>
                    <Upload {...props}>
                        <Button style={{
                            color: '#58BC58',
                            border: '1px solid #58BC58',
                            marginRight: '10px'
                        }} icon={<UploadOutlined />}>导入</Button>
                    </Upload>
                </Col>
                <ItemFrom classlist={classlist}  heardtitle={texts} setVisible={setVisible} visible={visible} getChildrenValue={updataItem} rowInfo={rowInfo}></ItemFrom>
            </Row>
            <Table
                rowKey='_id'
                columns={columns}
                dataSource={userlist}
                rowSelection={rowSelection}
                pagination={pagination}
                /* onRow={(record, index)=>{
                    return {
                        onClick:()=>{
                            onSelectRoW(index,record)
                        }
                    }
                }} */
            />
        </div>
    )
}

export default SchoolList